<script setup>
name: 'add'
import { ref, onMounted, computed, onBeforeUnmount, shallowRef } from 'vue'
import { useRouter } from 'vue-router';
import { getCategoriesListAPI, getparameterListAPI, addCartAPI } from '@/api/productAPI'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import _ from 'lodash'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 验证规则
const rules = {
    goods_name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' }
    ],
    goods_price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' }
    ],
    goods_number: [
        { required: true, message: '请输入商品数量', trigger: 'blur' }
    ],
    goods_weight: [
        { required: true, message: '请输入商品重量', trigger: 'blur' }
    ],
    goods_cat: [
        { required: true, message: '请输入商品分类', trigger: 'blur' }
    ],
}
const props = {
    value: 'cat_id',
    label: 'cat_name',
    expandTrigger: 'hover',
}

// 添加表单数据
const addForm = ref({
    goods_name: '',
    goods_price: 0,
    goods_number: 0,
    goods_weight: 0,
    goods_cat: [],
    pics: [],
    // 商品详情描述
    goods_introduce: '',
    attrs: []
})

const categorieslist = ref([])
const total = ref(0)
const getCategoriesList = async () => {
    const { data: res } = await getCategoriesListAPI()
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    categorieslist.value = res.data
    total.value = res.data.total
}

const active = ref('0')

const beforeTableLeave = () => {
    if (active.value === '0' && addForm.value.goods_cat.length === 0) {
        ElMessage.error('请选择商品分类')
        return false
    }
}

const roleId = computed(() => {
    if (addForm.value.goods_cat.length !== 0) {
        return addForm.value.goods_cat[addForm.value.goods_cat.length - 1]
    } else {
        return null
    }
})

const manyList = ref([])
const onlyList = ref([])

const getparameterList = async (roleId, activeName) => {
    const { data: res } = await getparameterListAPI(roleId, activeName)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : item.attr_vals
    });
    if (activeName === 'many') {
        manyList.value = res.data
    } else {
        onlyList.value = res.data
    }
}

const tabClicked = () => {
    if (active.value === '1') return getparameterList(roleId.value, 'many')
    if (active.value === '2') return getparameterList(roleId.value, 'only')
}

// 上传图片
const uploadURL = 'http://127.0.0.1:8888/api/private/v1/upload'
const userStore = useUserStore()
const { userInfo } = userStore
const headersObj = {
    Authorization: userInfo.token
}
const fileList = ref([])
// 预览图片地址
const previewPath = ref('')
// 删除图片列表
const handleRemove = (uploadFile, uploadFiles) => {
    addForm.value.pics = addForm.value.pics.filter(pic => {
        return pic.pic !== uploadFile.response.data.tmp_path
    })

}
const previewVisible = ref(false)
// 点击预览
const handlePreview = (file) => {
    // console.log(file)
    previewPath.value = file.url
    previewVisible.value = true
}
// 代码上传成功时
const handleSuccess = (response) => {
    const picInfo = {
        "pic": response.data.tmp_path
    }
    addForm.value.pics.push(picInfo)
}

const router = useRouter()

// 添加商品
const addFormRef = ref(null)
const addCate = async () => {
    addFormRef.value.validate(async valid => {
        if (!valid) return ElMessage.error('请填写必要的表单项')
        //执行添加的业务逻辑
        // 处理动态参数
        manyList.value.forEach(item => {
            const newInfo = {
                'attr_id': item.attr_id,
                'attr_value': item.attr_vals.join(' ')
            }
            addForm.value.attrs.push(newInfo)
        })
        // 处理静态属性
        onlyList.value.forEach(item => {
            const newInfo = {
                'attr_id': item.attr_id,
                'attr_value': item.attr_vals
            }
            addForm.value.attrs.push(newInfo)
        })
        const form = _.cloneDeep(addForm.value)
        form.goods_cat = form.goods_cat.join(',')
        const { data: res } = await addCartAPI(form)
        if (res.meta.status !== 201) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        router.push('/home/goods')
    })

}

onMounted(() => {
    getCategoriesList()
})

</script>

<template>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-alert title="添加商品信息" type="info" :closable="false" show-icon center />
        <el-steps :space="200" :active="active - 0" finish-status="success" align-center>
            <el-step title="基本信息" />
            <el-step title="商品参数" />
            <el-step title="商品属性" />
            <el-step title="商品图片" />
            <el-step title="商品内容" />
            <el-step title="完成" />
        </el-steps>
        <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px" label-position="top">
            <el-tabs tab-position="left" style="height: 200px" class="demo-tabs" v-model="active" stretch
                :before-leave="beforeTableLeave" @tab-change="tabClicked">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input type="number" v-model="addForm.goods_price"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input type="number" v-model="addForm.goods_weight"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input type="number" v-model="addForm.goods_number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader :options="categorieslist" v-model="addForm.goods_cat" :props="props">
                        </el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item :label="item.attr_name" v-for="item in manyList" :key="item.attr_id">
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox :label="param" v-for="(param, index) in item.attr_vals" :key="index" />
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item :label="item.attr_name" v-for="item in onlyList" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload class="upload-demo" :action="uploadURL" :headers="headersObj" :on-remove="handleRemove"
                        :on-preview="handlePreview" :on-success="handleSuccess" list-type="picture">
                        <el-button type="primary">上传图片</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png files with a size less than 500kb
                            </div>
                        </template>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <div style="border: 1px solid #ccc">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="addForm.goods_introduce"
                            :defaultConfig="editorConfig" @onCreated="handleCreated" />
                    </div>
                    <!-- 添加商品按钮 -->
                    <el-button type="primary" class="btnAdd" @click="addCate">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog title="图片预览" v-model="previewVisible" width="50%">
        <img :src="previewPath" class="previewImg" />
    </el-dialog>
</template>

<style lang="scss" scoped>
.el-tabs {
    height: 100% !important;
}

.previewImg {
    width: 100%;
}

.btnAdd {
    margin-top: 15px;
}
</style>